package com.innovate.nms.view;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.Timer;

import com.google.common.collect.Lists;
import com.ivan.toolkit.swing.ImagePanel;
import com.ivan.toolkit.swing.Images;

import lombok.Getter;
import lombok.Setter;

//@Log4j
public class SplashPanel extends JPanel {
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2405169372835909886L;
	
	private static Boss boss = new Boss();
	
	@Setter @Getter
	private boolean splash = false;
	private ImagePanel ipOrigin;
	private ImagePanel ipGray;


	/**
	 * Create the panel.
	 */
	public SplashPanel() {
		this.setBackground(Color.RED);
		this.setOpaque(true);
		boss.register(this);
		setLayout(new CardLayout(0, 0));
		
		ipGray = new ImagePanel();
		add(ipGray, "gray");
		
		ipOrigin = new ImagePanel();
		add(ipOrigin, "origin");

	}
	
	public void setImage(Image image) {
		
		if(image != null) {
			ipOrigin.setImage(image);
			ipGray.setImage(Images.gray(image));
		}
		
	}
	
	private void splash(boolean even) {
		
		CardLayout layout = (CardLayout)this.getLayout();
		
		if(splash && !even) {
			
			layout.show(this, "gray");
		} else {
			layout.show(this, "origin");
		}
		
		
	}
	
	public static class Boss implements ActionListener {
		
		private Timer timer = null; 
		
		private List<SplashPanel> panels = Lists.newLinkedList();
		
		private long tick = 0;
		
		void register(SplashPanel panel) {
			
			panels.add(panel);
			
			if(timer == null) {
				
				timer = new Timer(500, this);
				timer.start();
			}
			
		}


		@Override
		public void actionPerformed(ActionEvent e) {
			
			boolean even = (tick % 2) == 0;
			
			List<SplashPanel> temp = Lists.newLinkedList();
			temp.addAll(panels);
			
			//log.info("Splashing " + even);
			
			for(SplashPanel panel : panels) {
				
				panel.splash(even);
				
			}
			
			tick++;
			
		}
		
		
	}

}
